#include "tracvalidationwidget.h"
#include "ui_tracvalidationwidget.h"

#include "tracsettings.h"

#include <QtCore/QUrl>


namespace Trac {
namespace Internal {

TracValidationWidget::TracValidationWidget(QWidget *parent):
    QWidget(parent),
    ui(new Ui::TracValidationWidget),
    m_valid(false)
{
    ui->setupUi(this);
    ui->validationResultLabel->hide();
    connect(ui->anonymousCheckBox, SIGNAL(stateChanged(int)), this, SLOT(anonymousCheckBoxChanged(int)));
    connect(ui->usernameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkValid()));
    connect(ui->passwordLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkValid()));
    connect(ui->hostNameComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(hostChanged()));
    connect(ui->validatePushButton, SIGNAL(clicked()), this, SLOT(validatePushButtonClicked()));


    TracSettings::instance()->setHostName(ui->hostNameComboBox->currentText());
}

TracValidationWidget::~TracValidationWidget()
{
    delete ui;
}

bool TracValidationWidget::isValid() const
{
    return m_valid;
}

void TracValidationWidget::initialize()
{

}

void TracValidationWidget::anonymousCheckBoxChanged(int state)
{
    if(state == Qt::Checked) {
        ui->validationResultLabel->setVisible(false);

        ui->usernameLineEdit->clear();
        ui->passwordLineEdit->clear();

        TracSettings::instance()->setUsername("anonymous");
        TracSettings::instance()->setPassword("anonymous");
    }
    else if(state == Qt::Unchecked) {
        TracSettings::instance()->setUsername("");
        TracSettings::instance()->setPassword("");
    }

    ui->usernameLineEdit->setEnabled(!ui->anonymousCheckBox->isChecked());
    ui->passwordLineEdit->setEnabled(!ui->anonymousCheckBox->isChecked());

    m_valid = ui->anonymousCheckBox->isChecked();

    emit validChanged(m_valid);
}

void TracValidationWidget::validatePushButtonClicked()
{
    // TODO: validation

}

void TracValidationWidget::checkValid()
{
    if(ui->usernameLineEdit->text().isEmpty() || ui->passwordLineEdit->text().isEmpty())
        ui->validatePushButton->setEnabled(false);
    else
        ui->validatePushButton->setEnabled(true);

}

void TracValidationWidget::hostChanged()
{
    TracSettings::instance()->setHostName(ui->hostNameComboBox->currentText());
}

} // namespace Internal
} // namespace Trac

void Trac::Internal::TracValidationWidget::on_validatePushButton_clicked()
{

}
